import Vue from 'vue'
import router from '@/router'
import store from '@/store'
import JSZip from 'jszip'
import FileSaver from 'file-saver'

/**
 * 获取uuid
 */
export function getUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}

/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth(key) {
  return JSON.parse(sessionStorage.getItem('permissions') || '[]').indexOf(key) !== -1 || false
}

/**
 * 树形数据转换
 * @param {*} data list数据
 * @param {*} id 主键ID
 * @param {*} pid 上级ID
 * @param childrenKey 子list数据的key
 */
export function treeDataTranslate(data, id = 'id', pid = 'parentId', childrenKey = 'children') {
  let res = []
  let temp = {}
  for (let i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (let k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]][childrenKey]) {
        temp[data[k][pid]][childrenKey] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]][childrenKey].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}

/**
 * 根据orgNo翻译为orgName
 * @param orgNo
 */
export function transOrg(orgNo) {
  let orgList = JSON.parse(sessionStorage.getItem('orgList') || '[]')
  if (orgList.length > 0) {
    for (let i = 0; i < orgList.length; i++) {
      if (orgList[i].orgNo === orgNo) {
        return orgList[i].orgName
      }
    }
  }
  return '--'
}

/**
 * 根据userId翻译为realName
 * @param userId
 */
export function transUser(userId) {
  let userList = JSON.parse(sessionStorage.getItem('userList') || '[]')
  if (userList.length > 0) {
    for (let i = 0; i < userList.length; i++) {
      if (userList[i].userId === userId) {
        return userList[i].realName
      }
    }
  }
  return '--'
}

/**
 * 将数据字典的所有数据放到了前端缓存中
 * @param code
 * @param value
 * @returns {string|*}
 */
export function transDict(code, value) {
  if (!value && value !== 0) {
    return '--'
  }
  let dictList = JSON.parse(sessionStorage.getItem('dictList') || '[]')
  if (dictList.length > 0) {
    for (let i = 0; i < dictList.length; i++) {
      if (dictList[i].code === code && dictList[i].value.toString() === value.toString()) {
        return dictList[i].name
      }
    }
  }
  return '--'
}

/**
 * 清除登录信息
 */
export function clearLoginInfo() {
  Vue.cookie.delete('token')
  store.commit('resetStore')
  router.options.isAddDynamicMenuRoutes = false
}

/**
 * @param {date} time 需要转换的时间
 * @param {String} fmt 需要转换的格式 如 yyyy-MM-dd、yyyy-MM-dd HH:mm:ss
 */
export function formatTime(time, fmt) {
  if (!time) return ''
  else {
    const date = new Date(time)
    const o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'H+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds(),
      'q+': Math.floor((date.getMonth() + 3) / 3),
      S: date.getMilliseconds()
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + '').substr(4 - RegExp.$1.length)
      )
    }
    for (const k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length === 1
            ? o[k]
            : ('00' + o[k]).substr(('' + o[k]).length)
        )
      }
    }
    return fmt
  }
}

/**
 * 时分秒格式转时分
 * @param timestr
 * @returns {number}
 */
export function timeHMS2HM(timestr) {
  if (!timestr) return ''
  let timeItems = timestr.split(':')
  if (timeItems.length < 2) {
    return ''
  }
  return timeItems[0] + ':' + timeItems[1]
}

/**
 * 时分格式转时分秒
 * @param timestr
 * @returns {number}
 */
export function timeHM2HMS(timestr) {
  if (!timestr) return ''
  let timeItems = timestr.split(':')
  if (timeItems.length === 3) {
    return timestr
  }
  if (timeItems.length === 1) {
    return timeItems[0] + ':00:00'
  }
  return timeItems[0] + ':' + timeItems[1] + ':00'
}

/**
 * 下载文件通用方法
 * @param url
 * @param name
 */
export function downloadFile(url, name) {
  //  window.open(process.env.VUE_APP_BASE_API + "/hospital/file/downloadFile?tPath=" + tPath)
  //  const a = document.createElement('a')
  //  a.setAttribute('download', '活动方案.doc')
  //  a.setAttribute('target', '_blank')
  //  a.setAttribute('href', url)
  //  a.click()
  if (!url) {
    this.$message({
      message: '地址传入错误',
      type: 'error',
      duration: 1500
    })
    return
  }
  // 获取最后一个.的位置
  let index = url.lastIndexOf('.')
  // 获取后缀
  let ext = url.substr(index + 1)
  const elink = document.createElement('a')
  elink.download = name + '.' + ext
  elink.style.display = 'none'
  elink.href = url
  elink.target = '_blank'
  document.body.appendChild(elink)
  elink.click()
  URL.revokeObjectURL(elink.href) // 释放URL 对象
  document.body.removeChild(elink)
}

/**
 * 打包下载远程图片
 * @param arr 数组
 * @param blogTitle 下载压缩包名称
 * @constructor
 */
export function StoreDowQrcode(arr, blogTitle) {
  var zip = new JSZip()
  var imgs = zip.folder(blogTitle)
  var baseList = []
  var _this = this
  arr.forEach((item, index) => {
    var image = new Image()

    image.setAttribute('crossOrigin', 'anonymous')
    image.onload = function () {
      var canvas = document.createElement('canvas')
      canvas.width = image.width
      canvas.height = image.height

      var context = canvas.getContext('2d')
      context.drawImage(image, 0, 0, image.width, image.height)
      var url = canvas.toDataURL('image/png') // 得到图片的base64编码数据
      baseList.push({name: item.name, img: url.substring(22)})

      if (baseList.length === arr.length) {
        if (baseList.length > 0) {
          _this.$notify({
            title: '成功',
            message: '即将下载',
            type: 'success'
          })
          for (let k = 0; k < baseList.length; k++) {
            imgs.file(baseList[k].name + '.png', baseList[k].img, {
              base64: true
            })
          }
          zip.generateAsync({type: 'blob'}).then(function (content) {
            FileSaver.saveAs(content, blogTitle + '.zip')
          })
        } else {
          this.$message({
            message: '暂无图片可下载',
            type: 'error',
            duration: 1500
          })
        }
      }
    }
    image.src = item.url
  })
}
